package ar.com.nexttome.util;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import ar.com.nexttome.R;
import ar.com.nexttome.entities.Persona;
import ar.com.nexttome.tasks.DownloadFotoPerfilTask;

public class PersonaArrayAdapter extends ArrayAdapter<Persona> {
	private Context context;
	private ImageView foto;
	private TextView nick;
	private TextView distancia;
	private TextView id;
	private List<Persona> personas = new ArrayList<Persona>();

	public PersonaArrayAdapter(Context context, List<Persona> objects) {
		super(context, R.layout.personas, objects);

		this.context = context;
		this.personas = objects;
	}

	public int getCount() {
		return this.personas.size();
	}

	public Persona getItem(int index) {
		return this.personas.get(index);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// POR ACA PASA DOS VECES !!
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.personas, parent, false);

		Persona persona = getItem(position);

		foto = (ImageView) rowView.findViewById(R.id.foto);
		nick = (TextView) rowView.findViewById(R.id.nick);
		distancia = (TextView) rowView.findViewById(R.id.metros);
		id = (TextView) rowView.findViewById(R.id.tel);

		nick.setText(persona.getNick());
		distancia.setText(String.valueOf(persona.getDistancia()) + " mts");
		id.setText(String.valueOf(persona.getId()));

		DownloadFotoPerfilTask downloadFotoPerfilTask = new DownloadFotoPerfilTask(context,foto);
		downloadFotoPerfilTask.execute(persona.getId());

		return rowView;
	}

	/*
	 * The cancelPotentialWork method referenced in the code sample above checks if another running task
	 * is already associated with the ImageView. If so, it attempts to cancel the previous task by calling cancel().
	 * In a small number of cases, the new task data matches the existing task and nothing further needs to happen.
	 * Here is the implementation of cancelPotentialWork:
	 */
/*
	public static boolean cancelPotentialWork(String data, ImageView imageView) {
	    final DownloadFotoPerfilTask downloadFotoPerfilTask = getDownloadFotoPerfilTask(imageView);

	    if (downloadFotoPerfilTask != null) {
	        final String bitmapData = downloadFotoPerfilTask.id;
	        if (bitmapData != data) {
	            // Cancel previous task
	        	downloadFotoPerfilTask.cancel(true);
	        } else {
	            // The same work is already in progress
	            return false;
	        }
	    }
	    // No task associated with the ImageView, or an existing task was cancelled
	    return true;
	}
*/
}
